package es.udc.fic.hamNeggs.manager;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import es.udc.fic.hamNeggs.pojo.Project;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Repository(value = "project")
public class ProjectManager extends AbstractManager {
    private final static Logger LOG = Logger.getLogger(ProjectManager.class.getName());

    @Transactional(readOnly = true)
    @SuppressWarnings("unchecked")
    public List<Project> getProjectList() {
        List<Project> list = session.createQuery("from Project").list();

        Collections.sort(list,
                new Comparator<Project>() {
                    public int compare(Project o1, Project o2) {
                        return o1.getId().intValue() - o2.getId().intValue();
                    }
                });
        return list;
    }

    @Transactional(readOnly = true)
    public Project getProject(Long id) {
        Project prj = (Project) session.get(Project.class, id);
        return prj;
    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public Project getProject(String name) {
        List<Integer> projectID = session.createSQLQuery("select prj_id from hamneggs.projects where prj_name like '" +
                name + "';").list();
        if (projectID == null || projectID.isEmpty() || projectID.get(0) == null)
            return null;
        return getProject(new Long(projectID.get(0)));
    }

    @Transactional(readOnly = false)
    public void saveProject(Project project) {
        super.save(project, LOG);
    }

    @Transactional(readOnly = false)
    public void deleteProject(Project project) {
        super.delete(project, LOG);
    }

    @Transactional(readOnly = false)
    public void updateProject(Project project) {
        super.update(project, LOG);
    }

}
